package co.yixiang.modules.shop.rest;

import cn.hutool.core.date.DateUtil;
import co.yixiang.aop.log.Log;
import co.yixiang.modules.shop.domain.YxProductStockOut;
import co.yixiang.modules.shop.domain.YxStoreCategory;
import co.yixiang.modules.shop.domain.YxStoreProduct;
import co.yixiang.modules.shop.service.ProductStockOutService;
import co.yixiang.modules.shop.service.YxStoreProductService;
import co.yixiang.modules.shop.service.dto.ProductStockOutQueryCriteria;
import co.yixiang.utils.OrderUtil;
import co.yixiang.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URL;
import java.util.Date;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @author frq
 * @date 2020-5-15
 */
@Slf4j
@RestController
@RequestMapping("/api/productStockOut")
@Api(value = "外部商品管理", description = "外部商品数据管理")
public class ProductStockOutController {

    @Autowired
    private ProductStockOutService productStockOutService;

    @Autowired
    private YxStoreProductService storeProductService;

    //创建线程池
    static ExecutorService threadPool = Executors.newFixedThreadPool(10);
    //创建原生阻塞队列  队列最大容量为1000
    static BlockingQueue<String> queue = new ArrayBlockingQueue<String>(1000);


    @Log("查询外部商品列表")
    @GetMapping
    @ApiOperation("查询外部商品列表")
    public ResponseEntity<Object> getJdPhone(ProductStockOutQueryCriteria criteria, Pageable pageable) {
        return new ResponseEntity<>(productStockOutService.queryAll(criteria, pageable), HttpStatus.OK);

    }

    @Log("导出数据")
    @ApiOperation("导出数据")
    @GetMapping(value = "/download")
    public void download(HttpServletResponse response, ProductStockOutQueryCriteria criteria) throws IOException {
        productStockOutService.download(productStockOutService.queryAll(criteria), response);
    }

    @Log("导出外部商品图片")
    @GetMapping(value = "/doExportImages/{ids}")
    public void doExportImages(HttpServletResponse response, HttpServletRequest request, @PathVariable Integer[] ids) throws UnsupportedEncodingException {
        try {
            String dFilename = "商品图片.zip";//文件的名称
            // 指明response的返回对象是文件流
            response.setContentType("application/octet-stream");
            // 设置在下载框默认显示的文件名
            response.setHeader("Content-Disposition", "attachment;filename=" + dFilename);
            ZipOutputStream zos = new ZipOutputStream(response.getOutputStream());
            for (int i = 0; ids.length > i; i++) {
                YxProductStockOut productStockOut = productStockOutService.findById(ids[i]);
                if (productStockOut != null) {
                    String urlPath[] = productStockOut.getPicUrl().split(",");
                    for (int j = 0; urlPath.length > j; j++) {
                        String fname = DateUtil.format(new Date(), "HHmmssSSS") + "(" + (j + 1) + ")";
                        URL url = new URL(urlPath[j]);
                        //获取图片异常时，跳出本次循环执行下一次
                        InputStream fis = url.openConnection().getInputStream();
                        //在下载时，如果目录名称相同自动保存在同一目录下
                        zos.putNextEntry(new ZipEntry(productStockOut.getTitle().trim() + "/" + fname + ".jpg"));
                        byte[] buffer = new byte[1024];
                        int r = 0;
                        while ((r = fis.read(buffer)) != -1) {
                            zos.write(buffer, 0, r);
                        }
                        fis.close();
                    }
                }
            }
            zos.flush();
            zos.close();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    @Log("加入内部商品库")
    @ApiOperation("加入内部商品库")
    @GetMapping("/doAddInternal/{ids}")
    public void doAddInternal(@PathVariable Integer ids[]) {
        productStockOutService.doAddInternal(ids);
    }

    /**
     * 逻辑删除配置
     * @param ids
     * @return
     */
    @Log("删除")
    @ApiOperation("删除")
    @GetMapping("/doDeleteAll/{ids}")
    public ResponseEntity doDeleteAll(@PathVariable Integer ids[]){
        for (int i = 0; ids.length > i; i++) {
            productStockOutService.updateDel(ids[i],1);
        }
        return new ResponseEntity(HttpStatus.OK);
    }
    /**
     * 从回收站恢复商品
     * @param ids
     * @return
     */
    @Log("从回收站恢复商品")
    @ApiOperation("从回收站恢复商品")
    @GetMapping("/doRestoreGoodsAll/{ids}")
    public ResponseEntity doRestoreGoodsAll(@PathVariable Integer ids[]){
        for (int i = 0; ids.length > i; i++) {
            productStockOutService.updateDel(ids[i],0);
        }
        return new ResponseEntity(HttpStatus.OK);
    }
}
